package com.vpen.client.hello;

import cn.hutool.core.date.LocalDateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/11/24 16:45
 */
@Slf4j
@Component
@ClientEndpoint
public class HelloClientEndpoint {

    private static final String name = "Vpen";
    private static final String URL = "ws://localhost:8099/hello/";

    private static final ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();


//    @PostConstruct
    void init() {
        // 本机地址
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        try (Session session = container.connectToServer(HelloClientEndpoint.class, URI.create(URL + name))) {
            if (session != null) {
                sessionPools.put(name, session);
            }
        } catch (DeploymentException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 打开连接
     */
    @OnOpen
    public void onOpen(Session session) {
        log.debug("有连接创建");
        send("你好服务端，我是客户端", "vpen");
    }

    /**
     * 接收消息
     *
     * @param text -信息
     */
    @OnMessage
    public void onMessage(String text) {
        log.debug("来自服务器消息({})：{}", LocalDateTimeUtil.now(), text);
    }

    /**
     * 异常处理
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 关闭连接
     */
    @OnClose
    public void onClosing() throws IOException {
        log.debug("关闭");
    }

    /**
     * 主动发送消息
     */
    public void send(String message, String name) {
        Session session;
        if ((session = sessionPools.get(name)) != null) {
            session.getAsyncRemote().sendText(message);
        }
    }

}
